package com.zjlanyun.erp.interior.production;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.AndroidVersions;
import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.fntech.m10.gpio.M10_GPIO;
import com.fntech.m10a.gpio.M10A_GPIO;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Common;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.rfid.m10.u8.service.IOManager;
import com.zjlanyun.erp.rfid.m10.u8.service.SoundManager;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.utils.ViewUtil;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class MaterialCheck extends BaseRFIDActivity {

    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FNumber) TextView tv_FNumber;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.tv_FUnit) TextView tv_FUnit;
    @Bind(R.id.tv_FHeadExtStr01) TextView tv_FHeadExtStr01;
    @Bind(R.id.tv_FCLQty) TextView tv_FCLQty;
    //    @Bind(R.id.tv_FQty) TextView tv_FQty;
    @Bind(R.id.tv_Fresult) TextView tv_Fresult;
    @Bind(R.id.et_Fzhilangset2) EditText et_Fzhilangset2;
    @Bind(R.id.et_Fweight) EditText et_Fweight;
    @Bind(R.id.et_FBatchno) EditText et_FBatchno;
    @Bind(R.id.et_FQty) EditText et_FQty;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;
    @Bind(R.id.ll_submit) LinearLayout ll_submit;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private ArrayList<HashMap<String, Object>> mHegeList;
    public static SoundManager mSoundManager = new SoundManager();
    private String barcode = "";

    public static final int REQUESTCODE_SELECTHEGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.material_check);
        initBaseView();
        initView();
        initScan();
    }

    private void initView() {
        mHegeList = new ArrayList<>();
        apiUrl = WebApi.production();
        ll_submit.setVisibility(View.VISIBLE);
        title.setText("来料检验");

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tv_epc.getText().toString().equals("")) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    private void initScan() {
        mSoundManager.initSounds(this);
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
            IOManager.INSTANCE.InitComm(handler);
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
            IOManager.INSTANCE.InitCommA(handler);
        }
    }

    @Override
    protected void onResume() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
        }
        super.onResume();
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            epc = m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", "");
            getProductInfo();
        }
    }

    /**
     * 获取产品信息
     */
    private void getProductInfo() {
        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", epc);
        param.put("FActionFlag", "materialCheck");
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getProductInfo", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");

                if (data.optInt("FCLItemID") == 0) {
                    Toastor.getInstance().showShortToast("该卡没有绑定原料");
                    return;
                }

                tv_epc.setText(data.optString("epc"));
                tv_FGongxuName.setText(data.optString("FGongxuName"));
                tv_FName.setText(data.optString("FCLName"));
                tv_FNumber.setText(data.optString("FCLNumber"));
                tv_FModel.setText(data.optString("FCLModel"));
                tv_FUnit.setText(data.optString("FUnit"));
                tv_FHeadExtStr01.setText(data.optString("FHeadExtStr01"));
                tv_FCLQty.setText(data.optString("FCLQty"));
//                tv_FQty.setText(data.optString("FQty"));

                mHegeList = new ArrayList<HashMap<String, Object>>();
                JSONArray hege = data.optJSONArray("hege");
                for (int i = 0; i < hege.length(); i++) {
                    JSONObject item = hege.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    mHegeList.add(map);
                }
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                clean();
            }
        });
    }

    @OnClick(R.id.ll_submit)
    public void postMaterialCheck() {
        ViewUtil.hideInputMethod(mContext, ll_back);
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请先扫卡");
            return;
        }

        double Fweight;
        if (et_Fweight.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入重量");
            return;
        } else {
            Fweight = Double.valueOf(et_Fweight.getText().toString());
        }

        if (et_FQty.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入标签米数");
            return;
        } else if (et_FBatchno.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入批号");
            return;
        }


        HashMap<String, Object> param = new HashMap<>();
        param.put("epc", tv_epc.getText().toString());
        param.put("FResult", tv_Fresult.getText().toString());
        param.put("Fzhilangset2", et_Fzhilangset2.getText().toString());
        param.put("FActionFlag", "materialCheck");
        param.put("Fweight", Fweight);
        param.put("FBatchno", et_FBatchno.getText().toString());
        param.put("FQty", et_FQty.getText().toString());
        param.put("supplier", tv_FHeadExtStr01.getText().toString());
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postMaterialCheck", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                clean();
            }
        });
    }

    //选择是否合格
    @OnClick(R.id.btn_select_Fresult)
    public void select_hege() {
        if (mHegeList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择是否合格");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mHegeList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECTHEGE);
        } else {
            Toastor.getInstance().showShortToast("无数据");
        }
    }

    private void clean() {
        tv_epc.setText("");
        tv_FName.setText("");
        tv_FModel.setText("");
        tv_Fresult.setText("");
        et_Fzhilangset2.setText("");
        tv_FUnit.setText("");
        tv_FCLQty.setText("");
        tv_FHeadExtStr01.setText("");
        et_FQty.setText("");
        et_Fweight.setText("");
        et_FBatchno.setText("");
        tv_FNumber.setText("");
        tv_FGongxuName.setText("");
        barcode = "";
        epc = "";
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (!tv_epc.getText().toString().equals("")) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        } else if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            writeFile("/sys/class/gpio/gpio907/direction", "out");
            writeFile("/sys/class/gpio/gpio907/value", "0");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            writeFile("/sys/class/gpio/gpio907/value", "1");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECTHEGE && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            tv_Fresult.setText(mHegeList.get(p).get("FName").toString());
        }
    }

    private static void writeFile(String fileName, String writestr) {
        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = writestr.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    byte[] ret = (byte[]) msg.obj;
                    try {
                        barcode = new String(ret, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    System.out.println(barcode);
                    et_FBatchno.setText(barcode);
                    mSoundManager.playSound();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOff();
            IOManager.INSTANCE.DeInitComm();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOff();
            IOManager.INSTANCE.DeInitCommA();
        }
        super.onDestroy();
    }
}
